#include <SPI.h>
#include <WiFi.h>
#include <WebServer.h>
#include <TFT_eSPI.h> // Hardware-specific library
#include <qrcode_espi.h>

TFT_eSPI tft = TFT_eSPI(); // Invoke custom library
const char *AP_SSID = "Redmi K30S Ultra";
const char *AP_Password = "qwerty123";
WiFiServer esp32_server(8080);
QRcode_eSPI qrcode(&tft);

void setup(void)
{
  tft.init();
  pinMode(2, OUTPUT);
  pinMode(13, OUTPUT);
  tft.fillScreen(0xffa500);

  Serial.begin(115200);
  delay(500);
  Serial.println("111111111111");
  WiFi.begin(AP_SSID, AP_Password); // 设置AP模式热点的名称和密码
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(5000);
    Serial.println("正在连接");
    tft.println("正在连接");
  }
  Serial.println("连接成功");
  tft.setCursor(0, 0, 4);
  // Set "cursor" at top left corner of display (0,0) and select font 4
  tft.setTextColor(TFT_BLUE);
  tft.println("Connected");
  tft.println(WiFi.localIP());
  qrcode.init();
  // create qrcode
  //delay(50000);
  qrcode.create(WiFi.localIP().toString().c_str());
  esp32_server.begin();
}

void loop()
{
  WiFiClient client = esp32_server.available();
  String msgs = "";
  if (client)
  { 
    if(client.connected()){
      tft.fillScreen(0x42a5f5);
      tft.setTextColor(TFT_WHITE);
      tft.println("client Connected");
    }
    while (client.connected())
    {
      // while (client.available() > 0)
      // {                                         
      //   char c = client.read();
      //   Serial.println(c);
      //   msgs += c;
      // }
      if (client.available()) //如果有数据可读取
            {
                String line = client.readStringUntil('\n'); //读取数据到换行符
                Serial.print("读取到数据：");
                Serial.println(line);
                msgs = line + "\n";
                client.write(msgs.c_str()); //将收到的数据回发
                //tft.println(line.c_str());
                if(line=="123"){
                  digitalWrite(2, HIGH);
                  digitalWrite(13, HIGH);
                }else if(line=="456"){digitalWrite(2, LOW);digitalWrite(13, LOW);}
            }
      //client.print(msgs); // 将socket客户端接收的数据发送回去
      
      msgs = "";
      delay(10);
    }
    client.stop();
    qrcode.create(WiFi.localIP().toString().c_str());
    Serial.println("Client disconnected");
  }
}
